package com.ucode.tool.disruptor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 线程工厂
 * @author: liliang
 * @date: 2020年3月1日 下午12:42:15
 */
public class DisruptorThreadFactory implements ThreadFactory{

    private static final AtomicLong THREAD_NUMBER = new AtomicLong(1);

    /**
     * 线程组
     */
    private static final ThreadGroup THREAD_GROUP = new ThreadGroup("disruptor");

    /**
     * 是否是守护线程
     */
    private static volatile boolean daemon;

    /**
     * 线程名称前缀
     */
    private final String namePrefix;
    
    private DisruptorThreadFactory(final String namePrefix, final boolean daemon){
        this.namePrefix = namePrefix;
        DisruptorThreadFactory.daemon = daemon;
    }
    
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(THREAD_GROUP, r,
                THREAD_GROUP.getName() + "-" + namePrefix + "-" + THREAD_NUMBER.getAndIncrement());
        thread.setDaemon(daemon);
        if (thread.getPriority() != Thread.NORM_PRIORITY){
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
    
    /**
     * 自定义线程factory
     * @param namePrefix 线程名称前缀
     * @param daemon 是否是守护线程
     * @return
     */
    public static ThreadFactory create(final String namePrefix, final boolean daemon){
        return new DisruptorThreadFactory(namePrefix, daemon);
    }

}
